$(function(){
	var exam_id = $('#exam_id').val();
	if(exam_id!=null&&exam_id!=""&&exam_id!="null"){
		$.ajax({
			url:'student/startExam',
			type:'post',
			dataType:'json',
			async:false,
			data:{exam_id:exam_id},
			success:function(data){
				Modal.alert({msg:data.msg});
				if(data.success){
					//请求试卷信息
					$.ajax({
						url:'exam/loadPaper',
						type:'post',
						dataType:'json',
						data:{exam_id:exam_id},
						success:function(paper){
							//请求学生作答信息
							$.ajax({
								url:'exam/loadStuAnswer',
								type:'post',
								dataType:'json',
								data:{exam_id:exam_id},
								success:function(stuAnswer){
									/*
									 * 生成考试页面
									 */
									$('#paper_title').text(paper.title);
									$('#paper_time').text(paper.time);
									$('#paper_score').text(paper.score);
									//试卷body信息  
									var bodyHtml = "";
									
									var topics_scoreList = {};
									
									var topics_length = Object.keys(paper.topics).length;
									console.log(topics_length)
									
									var topics_score = parseFloat(0);
									for(var i=0;i<topics_length;i++){
										//遍历大题
										
										bodyHtml += '<div class="paper-topics-item">'+
											'<input type="hidden" class="topics-id" value='+paper.topics[i+1].id+'>'+
											'<input type="hidden" id="stuAnswer_id" value="'+stuAnswer.id+'">'+
											'<input type="hidden" class="topics-index-value" value='+paper.topics[i+1]._index+'>'+
											'<div class="paper-topics-index"><span>'+getTopicsIndex(paper.topics[i+1]._index)+'</span>、</div>'+
											'<div class="exam-topics-title">'+paper.topics[i+1].title+'</div>'+
											'<font class="paper-topics-score" color="blue"><i>(总分：<span class="exam-topics-score"></span>)</i></font>';
										var subtopics_length = Object.keys(paper.topics[i+1].subtopics).length;
										console.log('subtopicslength'+subtopics_length)
										for(var j=0;j<subtopics_length;j++){
											//遍历小题
											var stuOptions = {};
											
											for(var stu_o=0;stu_o<stuAnswer.stuOptions.length;stu_o++){
												if(stuAnswer.stuOptions[stu_o].subtopics.id==paper.topics[i+1].subtopics[j+1].id){
													//找到对应的学生作答项
													stuOptions = stuAnswer.stuOptions[stu_o].options;
													stuOptions_id = stuAnswer.stuOptions[stu_o].id;
													console.log(stuOptions)
												}
											}
											
											console.log("考生作答:"+JSON.stringify(stuOptions));
											
											topics_score += parseFloat(paper.topics[i+1].subtopics[j+1].score);
											
											var question_type = "";
												if(paper.topics[i+1].subtopics[j+1].single!=null){
													//单选题
													var single = paper.topics[i+1].subtopics[j+1].single;
													bodyHtml += '<div class="paper-subtopics-item">'+
																'<input type="hidden" class="stuoptions-id" value="'+stuOptions_id+'">'+
																'<input type="hidden" class="paper-subtopics-id" value='+paper.topics[i+1].subtopics[j+1].id+'>'+
																'<input type="hidden" class="question-id" value='+single.id+'>'+
																'<input type="hidden" class="question-num" value='+single.num+'>'+
																'<input type="hidden" class="question-type" value="Single">'+
																'<input type="hidden" class="subtopics-index-value" value='+paper.topics[i+1].subtopics[j+1]._index+'>'+
																'<div class="paper-subtopics-index"><span>'+paper.topics[i+1].subtopics[j+1]._index+'</span>、</div>'+
																'<div class="exam-subtopics-title">'+
																	single.title+
																'</div>'+
																'<font color="blue"><i>(单选题,'+paper.topics[i+1].subtopics[j+1].score+'分)</i></font>'+
																'<div class="paper-subtopics-body">';
													
													
													var length = Object.keys(single.options).length;
													for(var h=0;h<length;h++){
														
														bodyHtml += '<div class="subtopics-options-item">'+
																	'<input type="hidden" class="question-options-id" value='+single.options[optionsKey[h+1]].id+'>'+
																	'<input type="hidden" class="question-options-num" value='+single.options[optionsKey[h+1]].num+'>'+
																	'<div class="question-options-index">';
														if(stuOptions[1]!=null&&stuOptions[1].content==single.options[optionsKey[h+1]].id)
															bodyHtml += '<input checked ';
														else bodyHtml += '<input ';
														bodyHtml += 'onchange="selectRadio(this)" required type="radio" name="name_'+paper.topics[i+1]._index+'_'+paper.topics[i+1].subtopics[j+1]._index+'"><span>'+optionsKey[h+1]+'</span>.</div>'+
																	'<div class="exam-options-content" >'+
																		single.options[optionsKey[h+1]].content+
																	'</div>'+
																'</div>';
													}
													
													
													bodyHtml += '</div>'+
															'</div>';
												}else if(paper.topics[i+1].subtopics[j+1].multiple!=null){
													//多选题
													console.log('加载多选题答案:'+JSON.stringify(stuOptions))
													
													var isrequired = "required";
													if(Object.keys(stuOptions).length)
														isrequired = "";
													
													var multiple = paper.topics[i+1].subtopics[j+1].multiple;
													bodyHtml += '<div class="paper-subtopics-item">'+
													'<input type="hidden" class="paper-subtopics-id" value='+paper.topics[i+1].subtopics[j+1].id+'>'+
													'<input type="hidden" class="stuoptions-id" value="'+stuOptions_id+'">'+
														'<input type="hidden" class="question-id" value='+multiple.id+'>'+
														'<input type="hidden" class="question-num" value='+multiple.num+'>'+
														'<input type="hidden" class="question-type" value="Multiple">'+
														'<input type="hidden" class="subtopics-index-value" value='+paper.topics[i+1].subtopics[j+1]._index+'>'+
														'<div class="paper-subtopics-index"><span>'+paper.topics[i+1].subtopics[j+1]._index+'</span>、</div>'+
														'<div class="exam-subtopics-title">'+
															multiple.title+
														'</div>'+
														'<font color="blue"><i>(多选题,'+paper.topics[i+1].subtopics[j+1].score+'分)</i></font>'+
														'<div class="paper-subtopics-body">';
														var length = Object.keys(multiple.options).length;
														for(var h=0;h<length;h++){
											
															bodyHtml += '<div class="subtopics-options-item">'+
																		'<input type="hidden" class="question-options-id" value='+multiple.options[optionsKey[h+1]].id+'>'+
																		'<input type="hidden" class="question-options-num" value='+multiple.options[optionsKey[h+1]].num+'>'+
																		'<div class="question-options-index">';
															
															var sele_flag = false;
															var stu_a_l = Object.keys(stuOptions).length;
															for(var stu_i=0;stu_i<stu_a_l;stu_i++){
																if(stuOptions[stu_i+1].content==multiple.options[optionsKey[h+1]].id){
																	sele_flag = true;
																}
															}
															
															if(sele_flag)
																bodyHtml += '<input checked ';
															else bodyHtml += '<input ';
															
															bodyHtml += isrequired+' onclick="cbrequired(this)" onchange="selectMultiple(this)" type="checkbox" name="name_'+paper.topics[i+1]._index+'_'+paper.topics[i+1].subtopics[j+1]._index+'"><span>'+optionsKey[h+1]+'</span>.</div>'+
																		'<div class="exam-options-content" >'+
																			multiple.options[optionsKey[h+1]].content+
																		'</div>'+
																	'</div>';
														}
														
														bodyHtml += '</div>'+
																'</div>';
												}else if(paper.topics[i+1].subtopics[j+1].judgment!=null){
													//判断题
													var judgment = paper.topics[i+1].subtopics[j+1].judgment;
													bodyHtml += '<div class="paper-subtopics-item">'+
																'<input type="hidden" class="stuoptions-id" value="'+stuOptions_id+'">'+
																'<input type="hidden" class="paper-subtopics-id" value='+paper.topics[i+1].subtopics[j+1].id+'>'+
																'<input type="hidden" class="question-id" value='+judgment.id+'>'+
																'<input type="hidden" class="question-id" value='+judgment.num+'>'+
																'<input type="hidden" class="question-type" value="Judgment">'+
																'<input type="hidden" class="subtopics-index-value" value='+paper.topics[i+1].subtopics[j+1]._index+'>'+
																'<div class="paper-subtopics-index"><span>'+paper.topics[i+1].subtopics[j+1]._index+'</span>、</div>'+
																'<div class="exam-subtopics-title">'+
																judgment.title+
																'</div>'+
																'<font color="blue"><i>(判断题,'+paper.topics[i+1].subtopics[j+1].score+'分)</i></font>'+
																'<div class="paper-subtopics-body">';
																bodyHtml += '<div class="paper-subtopics-body">'+
																	'<div class="subtopics-options-item">';
																for(var k=0;k<judgment.options.length;k++){
																	bodyHtml += '<label>'+
																				'<input type="hidden" class="question-options-id" value='+judgment.options[k].id+'>'+
																				'<input type="hidden" class="question-options-num" value='+judgment.options[k].num+'>';
																	if(stuOptions[1]!=null&&stuOptions[1].content==judgment.options[k].id)
																		bodyHtml += '<input checked ';
																	else bodyHtml += '<input ';
																	bodyHtml += ' required value=true onchange="selectRadio(this)" type="radio" name="name_'+paper.topics[i+1]._index+'_'+paper.topics[i+1].subtopics[j+1]._index+'"><span>';
																	if(judgment.options[k].content=='true')bodyHtml +='正确';
																	else bodyHtml += '错误';
																	bodyHtml += '</span>&nbsp;&nbsp;</label>';	
																}
																bodyHtml += '</div>'+
																'</div>';
																				
																bodyHtml += '</div>'+
																		'</div>';
												}else if(paper.topics[i+1].subtopics[j+1].blank!=null){
													//填空题
													var blank = paper.topics[i+1].subtopics[j+1].blank;
														bodyHtml += '<div class="paper-subtopics-item">'+
																	'<input type="hidden" class="stuoptions-id" value="'+stuOptions_id+'">'+
																	'<input type="hidden" class="paper-subtopics-id" value='+paper.topics[i+1].subtopics[j+1].id+'>'+
																	'<input type="hidden" class="question-id" value='+blank.id+'>'+
																	'<input type="hidden" class="question-id" value='+blank.num+'>'+
																	'<input type="hidden" class="question-type" value="Blank">'+
																	'<input type="hidden" class="subtopics-index-value" value='+paper.topics[i+1].subtopics[j+1]._index+'>'+
																	'<div class="paper-subtopics-index"><span>'+paper.topics[i+1].subtopics[j+1]._index+'</span>、</div>'+
																	'<div onkeyup="divInputChange(this)" class="exam-subtopics-title">';
														
														var contentDOM = $('<body></body>');
														$(contentDOM).html(blank.title);
														
														var blank_list = $(contentDOM).find('input');
														for(var x=0;x<blank_list.length;x++){
															$(blank_list[x]).attr('onchange','answerBlank(this)');
															
															if(stuOptions[x+1]!=null){
																console.log('class'+$(blank_list[x]).attr('class'));
																$(blank_list[x]).attr('content',stuOptions[x+1].content);
															}
														}
														bodyHtml += $(contentDOM).html();
														
														console.log('blank的题干:'+$(contentDOM).html())
														
														bodyHtml +=	'</div>'+
																'<font color="blue"><i>(填空题,'+paper.topics[i+1].subtopics[j+1].score+'分)</i></font>'+
																'<div class="paper-subtopics-body">';
														bodyHtml += '</div>'+
																'</div>';
												}else if(paper.topics[i+1].subtopics[j+1].explanation!=null){
													//解答题
													var explanation = paper.topics[i+1].subtopics[j+1].explanation;
													bodyHtml += '<div class="paper-subtopics-item">'+
																'<input type="hidden" class="stuoptions-id" value="'+stuOptions_id+'">'+
																'<input type="hidden" class="paper-subtopics-id" value='+paper.topics[i+1].subtopics[j+1].id+'>'+
																'<input type="hidden" class="question-id" value='+explanation.id+'>'+
																'<input type="hidden" class="question-num" value='+explanation.num+'>'+
																'<input type="hidden" class="question-type" value="Explanation">'+
																'<input type="hidden" class="subtopics-index-value" value='+paper.topics[i+1].subtopics[j+1]._index+'>'+
																'<div class="paper-subtopics-index"><span>'+paper.topics[i+1].subtopics[j+1]._index+'</span>、</div>'+
																'<div class="exam-subtopics-title">'+
																	explanation.title+
																'</div>'+
																'<font color="blue"><i>(解答题,'+paper.topics[i+1].subtopics[j+1].score+'分)</i></font>'+
																'<div class="paper-subtopics-body">'+
																'</div>';
													bodyHtml += '<div class="question-answer">答：'+
														'<textarea required onchange="answerExpl(this)" class="form-control answer-textarea question-options-content">';
														if(stuOptions[1]!=null)
															bodyHtml += stuOptions[1].content;
													bodyHtml += '</textarea>'+
															'</div>'+
														'</div>';
												}else{
													
												}
										}
										$(topics_scoreList).attr(i,topics_score);
										bodyHtml += '</div>';
									}
									$('.exam-body').html(bodyHtml);
									
									$('.answer-textarea').autoHeight();
									
									var blanks_ = $('.the-blank');
									for(var b_i=0;b_i<blanks_.length;b_i++){
										$(blanks_[b_i]).val(($(blanks_[b_i]).attr('content')));
										$(blanks_[b_i]).removeAttr('content');
									}
									
									var score_length = Object.keys(topics_scoreList).length;
									var scoreElems = $('.exam-topics-score');
									for(var s_i=0;s_i<score_length;s_i++){
										$(scoreElems[s_i]).text(topics_scoreList[s_i]);
									}
									
									$.ajax({
										url:'exam/getCurrentDate',
										type:'post',
										dateType:'json',
										success:function(date){
											if(date==null){
												alert("获取服务器时间出错!");
												window.location.href="stu_index";
											}else{
												var paper_time = paper.time;
												var exam_date = $('#exam_date').val();
												var endTime = parseInt(exam_date)+parseInt(paper_time*60*1000);
												timeInterval(parseInt((endTime-date)/1000));
											}
										},
										error:function(){
											alert('出错了...');
											window.location.href="stu_index";
										}
									});
									
								},
								error:function(){
									Modal.alert({msg:'出错了...'});
								}
									
							});
						},
						error:function(){
							Modal.alert({msg:'出错了...'});
						}
					});
				}
			},
			error:function(){
				Modal.alert({msg:'出错！'});
			}
		});
	}else{
		window.location.href="stu_index";
	}
});

function getCnIndex(num){
	return (0==num)?"零":(1==num)?"一":(2==num)?"二":(3==num)?"三":(4==num)?"四":(5==num)?"五":(6==num)?"六":(7==num)?"七":(8==num)?"八":(9==num)?"九":(10==num)?"十":(100==num)?"百":"";
}
function getTopicsIndex(num){
	//获取大题中文题标
	var index_1 = num%10;
	var index_10 = parseInt((num%100)/10);
	var index_100 = parseInt(num/100);
	return (num>0&&num<10)?getCnIndex(num):(num==10)?'十':(num>10&&num<20)?("十"+getCnIndex(index_1)):(num>=20&&num<100)?(getCnIndex(index_10)+"十"+getCnIndex(index_1)):(num>=100&&num<1000)?(getCnIndex(index_100)+"百"+getCnIndex(index_10)+"十"+getCnIndex(index_1)):"";
}
var optionsKey={
		"1":"A","2":"B","3":"C","4":"D","5":"E","6":"F","7":"G","8":"H","9":"I","10":"J","11":"K","12":"L","13":"M","14":"N","15":"O","16":"P","17":"Q","18":"R","19":"S","20":"T","21":"U","22":"V","23":"W","24":"X","25":"Y","26":"Z"
};
function cbrequired(obj){
	//复选框非空
	if($('input[name="'+$(obj).attr("name")+'"]:checked').length<=0){
		$($('input[name="'+$(obj).attr("name")+'"]')[0]).prop('required','required');
	}else{
		$('input[name="'+$(obj).attr("name")+'"]').removeProp('required');
	}
}

//选择答案事件！！！！
function selectRadio(obj){
	var stuOptions_id = $(obj).parents('.paper-subtopics-item').find('.stuoptions-id').val();
	var subtopics_id = $(obj).parents('.paper-subtopics-item').find('.paper-subtopics-id').val();
	var option_content = $(obj).parents('.subtopics-options-item').find('.question-options-id').val();
	var option_num = newGuid();
	var resultJSON = {
			'id':stuOptions_id,
			'subtopics':{'id':subtopics_id},
			'options':{
				'1':{
					'num':option_num,
					'content':option_content
					}
				}
			};
	var result = JSON.stringify(resultJSON);
	console.log(result)
	$.ajax({
		url:'stuAnswer/selectAnswer',
		type:'post',
		dataType:'json',
		data:{stuOptions:result},
		success:function(data){
			//Modal.alert({msg:data.msg});
		},
		error:function(){
			Modal.alert({msg:'出错！'});
		}
	});
}
//选择多选题
function selectMultiple(obj){
	
	var stuOptions_id = $(obj).parents('.paper-subtopics-item').find('.stuoptions-id').val();
	var subtopics_id = $(obj).parents('.paper-subtopics-item').find('.paper-subtopics-id').val();
	
	var resultJSON = {
			'id':stuOptions_id,
			'subtopics':{'id':subtopics_id}
			};
	
	var selects = $('input[name="'+$(obj).attr('name')+'"]:checked');
	
	var options = {};
	
	for(var i=0;i<selects.length;i++){
		var option_content = $(selects[i]).parents('.subtopics-options-item').find('.question-options-id').val();
		var option_num = newGuid();
		$(options).attr(i+1,{'num':option_num,'content':option_content});
	}
	$(resultJSON).attr('options',options);
	var result = JSON.stringify(resultJSON);
	console.log(result)
	$.ajax({
		url:'stuAnswer/selectAnswer',
		type:'post',
		dataType:'json',
		data:{stuOptions:result},
		success:function(data){
			//Modal.alert({msg:data.msg});
		},
		error:function(){
			Modal.alert({msg:'出错！'});
		}
	});
}
//填空
function answerBlank(obj){
	var blanks = $(obj).parents('.exam-subtopics-title').find('input[type="text"]');
	var stuOptions_id = $(obj).parents('.paper-subtopics-item').find('.stuoptions-id').val();
	var subtopics_id = $(obj).parents('.paper-subtopics-item').find('.paper-subtopics-id').val();
	
	var options = {};
	for(var i=0;i<blanks.length;i++){
		var option_content = $(blanks[i]).val();
		var option_num = newGuid();
		$(options).attr(i+1,{'num':option_num,'content':option_content});
	}
	
	var resultJSON = {
			'id':stuOptions_id,
			'subtopics':{'id':subtopics_id}
			};
	
	$(resultJSON).attr('options',options);
	var result = JSON.stringify(resultJSON);
	console.log(result)
	$.ajax({
		url:'stuAnswer/selectAnswer',
		type:'post',
		dataType:'json',
		data:{stuOptions:result},
		success:function(data){
			//Modal.alert({msg:data.msg});
		},
		error:function(){
			Modal.alert({msg:'出错！'});
		}
	});
}
//解答
function answerExpl(obj){
	var stuOptions_id = $(obj).parents('.paper-subtopics-item').find('.stuoptions-id').val();
	var subtopics_id = $(obj).parents('.paper-subtopics-item').find('.paper-subtopics-id').val();
	
	var options = {};
	var option_num = newGuid();
	var option_content = $(obj).val();
	$(options).attr('1',{'num':option_num,'content':option_content});
	
	var resultJSON = {
			'id':stuOptions_id,
			'subtopics':{'id':subtopics_id}
			};
	$(resultJSON).attr('options',options);
	var result = JSON.stringify(resultJSON);
	console.log(result)
	$.ajax({
		url:'stuAnswer/selectAnswer',
		type:'post',
		dataType:'json',
		data:{stuOptions:result},
		success:function(data){
			//Modal.alert({msg:data.msg});
		},
		error:function(){
			Modal.alert({msg:'出错！'});
		}
	});
}
//交卷
$('#answer_commit_form').submit(function(event){
	var stuAnswer_id = $('#stuAnswer_id').val();
	$.ajax({
		url:'stuAnswer/commit',
		type:'post',
		dataType:'json',
		data:{stuAnswerId:stuAnswer_id,isTimeUp:false},
		success:function(data){
			alert(data.msg);
			if(data.success){
				window.location.href="stu_index";
			}
		},
		error:function(){
			alert('出错了...');
		}
	});
	return false;
});
/*生成唯一num*/
function newGuid()  
{  
    var guid = "";  
    for (var i = 1; i <= 32; i++){
      var n = Math.floor(Math.random()*16.0).toString(16);  
      guid +=   n;  
      if((i==8)||(i==12)||(i==16)||(i==20))  
        guid += "-";
    }  
    return guid;      
}
/*填空宽度控制*/
var textWidth = function(text){ 
    var sensor = $('<pre>'+ text +'</pre>').css({display: 'none'}); 
    $('body').append(sensor); 
    var width = sensor.width();
    sensor.remove();
    return width;
};
function changeText(obj){
    $(obj).width(textWidth($(obj).val())+30);
}
//计时器
function timeInterval(time){
	$("#rest_time").html(parseInt((time)/60)+':'+time%60);
	var timeSec = time-1;
	var timeStr = '';
	var codeTime = setInterval(function Internal(){
		if (timeSec <= 0){
			//Long stuAnswerId,boolean isTimeUp
			//强制交卷
			var stuAnswerId = $('#stuAnswer_id').val();
			$.ajax({
				url:'stuAnswer/commit',
				type:'post',
				dataType:'json',
				data:{stuAnswerId:stuAnswerId,isTimeUp:true},
				success:function(data){
					alert(data.msg);
					if(data.success){
						window.location.href="stu_index";
					}
				},
				error:function(){
					alert('出错了...');
				}
			});
	    }
		timeStr = parseInt((timeSec)/60)+':'+timeSec%60;
		$("#rest_time").html(timeStr);
		timeSec--;
	},1000);
}
window.onbeforeunload = function(){
	return '确认要离开页面吗?';
}